package com.cloud.common.feign.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Objects;

/**
 * 使用feign请求服务时，附带上登录信息
 *
 * @author yan
 */
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //feign 使用的是线程池模式，当开启熔断的时候，feign 所在的服务端不在同一个线程，这是attributes取到的将会是空值
        /*if (Objects.isNull(attributes)) {
            return;
        }*/
        HttpServletRequest request = attributes.getRequest();
        if (Objects.isNull(request)) {
            return;
        }
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                requestTemplate.header(name, values);
            }
        }
    }
}
